package top.heue.utils.base.util.view

import android.widget.EditText
import androidx.core.widget.doOnTextChanged

object EditUtil {
    fun initOnWord(exceptRegex: Regex ,editText: EditText, onWord: (String) -> Unit) {
        editText.doOnTextChanged { text, _, _, _ ->
            //字符串为null不继续
            if (text == null) return@doOnTextChanged
            //输入文字继续
            val aboveWord = StringBuffer("")
            var abovePos = editText.selectionStart - 1
            while (true) {
                if (abovePos < 0) break
                val c = text[abovePos--]
                if (exceptRegex.matches(c.toString())) {
                    break
                }
                aboveWord.insert(0, c)
            }
            //aboveWord就是得到的输入的最近的词
            onWord(aboveWord.toString())
        }
    }
}